package com.licheng.aop;

import com.licheng.mapper.LoginMapper;
import com.licheng.pojo.Emp;
import com.licheng.pojo.EmpLoginLog;
import com.licheng.pojo.LoginInfo;
import com.licheng.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

//@Aspect
@Slf4j
@Component
public class LoginLogAspect {

    @Autowired
    LoginMapper loginMapper;

    @Around("execution(* com.licheng.controller.LoginController.*(..))")
    public Object loginLog(ProceedingJoinPoint pjp) throws Throwable {
        short isSuccess = 0;
        String token = "";
        Object[] args = pjp.getArgs();
        Emp emp = (Emp) args[0];
        //获取登录的用户名和密码
        String username = emp.getUsername();
        String password = emp.getPassword();
        //操作时间
        LocalDateTime loginTime = LocalDateTime.now();
        long start = System.currentTimeMillis();
        //原始方法的返回值
        Object proceed = pjp.proceed();
        Result result = (Result)proceed;
        long end = System.currentTimeMillis();
        //登录操作耗时
        long costTime = end - start;


        if (result.getCode() == 1) {
            isSuccess = 1;
            //成功得到token
            LoginInfo loginInfo = (LoginInfo) result.getData();
            token = loginInfo.getToken();
        }

        EmpLoginLog empLoginLog = new EmpLoginLog(null, username,
                password, loginTime, isSuccess, token, costTime);
        //插入日志数据到数据库
        loginMapper.insertLoginLog(empLoginLog);

        return proceed;
    }
}
